"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
exports.__esModule = true;
var context_1 = require("./context");
var typeorm_1 = require("typeorm");
var _ = require("lodash");
var youngService = /** @class */ (function (_super) {
    __extends(youngService, _super);
    function youngService() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.entity = null;
        _this.searchOption = {
            keywords: [],
            fieldEq: [],
            fieldStatus: {},
            size: 20,
            page: 1,
            order: {}
        };
        return _this;
    }
    /**
     * 获取列表
     * @returns
     */
    youngService.prototype.list = function () {
        return __awaiter(this, void 0, void 0, function () {
            var where, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.check();
                        return [4 /*yield*/, this.where()];
                    case 1:
                        where = _b.sent();
                        _a = this.success;
                        return [4 /*yield*/, where.getMany()];
                    case 2: return [2 /*return*/, _a.apply(this, [_b.sent()])];
                }
            });
        });
    };
    /**
     * 拼装SQL
     * @returns
     */
    youngService.prototype.where = function () {
        return __awaiter(this, void 0, void 0, function () {
            var where, string, k, i, f;
            var _this = this;
            return __generator(this, function (_a) {
                where = this.getRepository().createQueryBuilder().where("1 = 1");
                if (this.searchOption.fieldEq.length) {
                    this.searchOption.fieldEq.forEach(function (f) {
                        if (_this.body[f]) {
                            var p = [];
                            p[f] = _this.body[f];
                            where = where.andWhere("".concat(f, " = :").concat(f), p);
                        }
                    });
                }
                if (this.searchOption.fieldStatus) {
                    _.forEach(this.searchOption.fieldStatus, function (value, key) {
                        var p = {};
                        p[key] = value;
                        where = where.andWhere("".concat(key, " = :").concat(key), p);
                    });
                }
                if (this.searchOption.keywords.length && this.body.keywords) {
                    string = "( ";
                    k = this.body.keywords;
                    for (i = 0; i < this.searchOption.keywords.length; i++) {
                        f = this.searchOption.keywords[i];
                        if (i == 0)
                            string += "".concat(f, " like \"%").concat(k, "%\"");
                        else
                            string += " or ".concat(f, " like \"%").concat(k, "%\"");
                    }
                    string += " )";
                    where = where.andWhere(string);
                }
                if (this.searchOption.order || this.body.order) {
                    _.forEach(this.searchOption.order, function (value, key) {
                        where = where.addOrderBy(key, value.toUpperCase());
                    });
                    _.forEach(this.body.order, function (value, key) {
                        where = where.addOrderBy(key, value.toUpperCase());
                    });
                }
                return [2 /*return*/, where];
            });
        });
    };
    /**
     * 分页获取
     * @returns
     */
    youngService.prototype.page = function () {
        return __awaiter(this, void 0, void 0, function () {
            var size, page, where, data;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.check();
                        size = (this.body.size ? parseInt(this.body.size) : 0) || this.searchOption.size;
                        page = (this.body.page ? parseInt(this.body.page) : 0) || this.searchOption.page;
                        return [4 /*yield*/, this.where()];
                    case 1:
                        where = _a.sent();
                        where = where.take(size).skip((page - 1) * size);
                        return [4 /*yield*/, where.getManyAndCount()];
                    case 2:
                        data = _a.sent();
                        return [2 /*return*/, this.success({
                                list: data[0],
                                pagination: { total: data[1], page: page, size: size }
                            })];
                }
            });
        });
    };
    /**
     * sql分页获取
     * @param sql 分页获取的sql
     * @param params 分页获取的参数
     * @returns 分页数据
     */
    youngService.prototype.sqlPage = function (sql, params) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, _b, order, _c, page, _d, size, limit, orderStr, data, total;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        _a = this.body, _b = _a.order, order = _b === void 0 ? { createTime: "desc" } : _b, _c = _a.page, page = _c === void 0 ? 1 : _c, _d = _a.size, size = _d === void 0 ? 10 : _d;
                        limit = (page - 1) * size;
                        orderStr = "order by ";
                        _.forEach(order, function (val, key) {
                            orderStr += "".concat(key, " ").concat(val);
                        });
                        _.trim(orderStr, ",");
                        return [4 /*yield*/, this.sql("".concat(sql, " ").concat(orderStr, " limit ").concat(limit, ",").concat(size), params)];
                    case 1:
                        data = _e.sent();
                        return [4 /*yield*/, this.sql("select count(*) as total from (" + sql + ")  as t1", params)];
                    case 2:
                        total = _e.sent();
                        return [2 /*return*/, {
                                list: data,
                                pagination: {
                                    total: total.length ? Number(total[0].total) : 0,
                                    page: page,
                                    size: size
                                }
                            }];
                }
            });
        });
    };
    /**
     * 详情
     * @returns 单行数据
     */
    youngService.prototype.info = function () {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.check();
                        id = this.query.id;
                        if (!id)
                            throw new Error("请传入id");
                        return [4 /*yield*/, this.getRepository().findOne({ id: id })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * 新增
     * @returns
     */
    youngService.prototype.add = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.check();
                        return [4 /*yield*/, this.getRepository().insert(this.body)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, this.success(this.body)];
                }
            });
        });
    };
    /**
     * 更新
     * @returns
     */
    youngService.prototype.update = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.check();
                        if (!this.body.id)
                            throw new Error("请传入id");
                        return [4 /*yield*/, this.getRepository().update({ id: this.body.id }, this.body)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, this.success()];
                }
            });
        });
    };
    /**
     * 删除
     * @returns
     */
    youngService.prototype["delete"] = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.check();
                        if (!this.body.ids)
                            throw new Error("请传入ids");
                        return [4 /*yield*/, this.getRepository()["delete"]({
                                id: (0, typeorm_1.In)(this.body.ids.toString().split(","))
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, this.success()];
                }
            });
        });
    };
    /**
     * 获取数据模型
     */
    youngService.prototype.getRepository = function () {
        if (typeof this.entity == "string") {
            return this.app.orm[this.entity];
        }
        else {
            return this.app.orm.getRepository(this.entity);
        }
    };
    /**
     * 数据库原生语句查询
     * @param sql
     * @param param
     * @returns
     */
    youngService.prototype.sql = function (sql, param) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.app.orm)
                            throw new Error("请先配置数据库链接");
                        return [4 /*yield*/, this.app.orm.manager.query(sql, param)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * 检测是否注册实体
     */
    youngService.prototype.check = function () {
        if (this.entity === null)
            throw new Error("请指定实体");
    };
    /**
     * 成功返回处理
     * @param data 返回数据
     * @returns
     */
    youngService.prototype.success = function (data) {
        data = data || "请求成功";
        return { code: 1000, data: data };
    };
    /**
     * 失败返回处理
     * @param msg 错误信息
     * @returns
     */
    youngService.prototype.error = function (msg) {
        return { code: 1001, msg: msg };
    };
    return youngService;
}(context_1.youngCore));
module.exports = youngService;
